package com.ItemsRent.IService.service;


import java.security.MessageDigest;

import com.ItemsRent.IDao.dao.BaseDAO;
import com.ItemsRent.IService.ICustomer;
import com.ItemsRent.model.Customer;

/**
 * 
 * @author yrf
 *
 */
public class CustomerServiceImpl implements ICustomer{
	
	private BaseDAO<Customer> customerDao;

	public BaseDAO<Customer> getCustomerDao() {
		return customerDao;
	}

	public void setCustomerDao(BaseDAO<Customer> customerDao) {
		this.customerDao = customerDao;
	}
	/**
	 * @功能：查询用户是否存在
	 * @author yrf
	 * @param stuNumber
	 * @param password
	 * @return
	 */
	public Customer getCustomer(String stuNumber, String password){
		//Customer customer = customerDao.find(Customer.class, 2);
		password = encryptByMD5(password);
		String hql = "select c from Customer c where c.number = '"+stuNumber+"' and c.customerPassword = '"+password+"' ";
		
		Customer customer = customerDao.find(hql);
		if(customer!=null){
			if(customer.getCustomerPassword().equals(password.trim())){
				return customer;
			}
		}
		/*List<Customer> list = (List<Customer>)customerDao.list(hql);
		if(list==null||list.size()==0){
			System.out.println("There is no " +stuNumber);
			return null;
		}else if(list.get(0).getCustomerPassword().equals(password.trim())){
			return list.get(0);
		}*/
		return null;
	}
	
	/**
	 * 返回十六进制字符
	 * @author yrf
	 * @param b
	 * @return
	 */
	public String byte2HexString(byte[] b){
		StringBuffer hs = new StringBuffer();
		String tmp = "";
		for(int i = 0; i<b.length; i++){
			tmp = Integer.toHexString(b[i] & 0xff);
			if(tmp.length()==1)
				hs.append("0"+tmp);
			else 
				hs.append(tmp);
		}
		return hs.toString();
	}
	
	/**
	 * 进行MD5加密
	 * @author yrf
	 * @param str
	 * @return
	 */
	public String encryptByMD5(String str){
		if(str == null) return "";
		byte[] b = null;
		try{
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			b = md.digest();
		}catch(Exception ex){
			System.out.println(ex);
		}
		return byte2HexString(b);
	}

	@Override
	public void update(Customer customer) {
		// TODO Auto-generated method stub
		customerDao.update(customer);
	}

}
